package com.ljsw.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.hdhe.uhf.main.SaomiaoUtil;
import com.android.hdhe.uhf.main.Util;
import com.android.hdhe.uhf.reader.CaseString;
import com.android.hdhe.uhf.reader.UhfReader;
import com.ljsw.activity.R;
import com.ljsw.application.App;
import com.ljsw.dialog.DeleteDialog;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.UserLoginDialog;
import com.ljsw.dialog.ZzxDialog;
import com.ljsw.entity.RenWuClass;
import com.ljsw.entity.User;
import com.ljsw.server.UpServer;
import com.ljsw.util.Constant;
import com.ljsw.util.DecodeLock;
import com.ljsw.util.DialogManager;
import com.ljsw.util.FingerUtil;
import com.ljsw.util.FingerUtil.OnGetFingerListener;
import com.poka.device.RFIDDevice;
import com.poka.entity.ReciveList;
import com.poka_global_constant.GlobalConstant;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static android.util.Log.e;

/**
 * 库管员验证指纹 页面进行指纹验证 目前是指纹完之后点击弹出提示框 作者: 石锚 版本: 1.0 日期: 2015-10-21
 */
public class KuguanFragment extends BaseFragment implements OnClickListener, OnGetFingerListener {
    
	private static final String TAG = "KuguanFragment";
    private TextView top;// 顶部提示
    private TextView kg_name1, kg_name2;// 顶部提示
    private View view;
    private ImageView leftImage, rightImage;// 左边指纹 右边指纹
    private FragmentManager fm;
    private DialogManager dialogManager;// 弹出框管理类
    private ZzxDialog zzxDialog;// 周转箱弹出框
    private DeleteDialog deleteDialog;// 删除弹出框
    private LoginDialog loginDiolag;// 获取任务Dialog
    private Bundle bundle;
    private Handler handler;
    private String cid;// 车牌号
    private String paigongdan = "";// 派工单
    private ArrayList<String> list = new ArrayList<String>();// 要扫描的集合数据
    private ArrayList<String> listtest = new ArrayList<String>();// 要扫描的集合数据
    private ArrayList<String> boxlist = new ArrayList<String>();// 传扫描的集合数据
    private ArrayList<String> copylist = new ArrayList<String>();// 传扫描的集合数据
    private LinearLayout zxlist_layout,// 填充器（美化UI,周转箱）
            zxlist_layout_view;// 填充器（周转箱列表）

    private App app;// 全局变量
    private Button btn;
    private Bitmap bmp;
    private ArrayList<RenWuClass> wancenglist;

    private UserLoginDialog useDialog;// 用户登录弹出框
    private String userId;// 用户登录的账号
    private String pwd;// 用户登录的密码
    private User user;
    private String kuId = "";// 库管员Id
    private TextView startsaomiao;// 开始扫描
    private TextView zzxclear;// 清空周转箱，重扫

    private String fristUserId = null;// 用户登录的密码
    private boolean flag = true;// 标识是否是第一个人登录
    private UhfReader reader; // 超高频读写器
    private SaomiaoUtil saomiao;
    private FingerUtil mFingerUtil;// 指纹验证工具类
    private int times = 0;// 验证失败超过3次弹出窗口
    private boolean threeTimes = false;// 失败累计三次
    private final static String DEPARTMENT_ID = "988050000";// 总库库管机构ID  20190629更改
    private int testint; //测试得到穿过去几个锁号
    /*
     * 为密码锁功能所添加的变量声明
     * @author zhouKai
     */
    private RadioGroup rg_zzx_num;    //周转箱编号单选组
    private Button btn_lock_zzx;    // 闭锁
    private Button btn_unLock_zzx;    //开锁
    private DecodeLock decodeLock; // 密码锁对象
    private TextView zzx_queren;    // 扫描确认按钮
    private TextView tvsuohao;    // 显示锁号
    private boolean istestflag = false;  //是否循环进行开锁

    // 新版的开锁
    private RFIDDevice rfidDevice;
    private ReciveList receivelist;
    private String selectItem = "";

    private final int OPEN_LOCK = 1;
    private final int CLOSE_LOCK = 0;

    private RFIDDevice.OnDataReceiveListener listener = null;
    private String operator = null;
    ArrayList<String> LockID = new ArrayList<String>();//c存放锁号码
    private Handler handlerzhuan;
    private ArrayList<String> listzou = new ArrayList<String>();//周转箱号放入集合
    private Long LastClickTime;//最后一次点击时间
    private Long LastClickTime1;
    private Long lctime;

    @SuppressLint("HandlerLeak")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_kugaun, container, false);
        app = (App) getActivity().getApplication();
        // 获取读写器实例，若返回Null,则串口初始化失败
        reader = UhfReader.getInstance();
        Util.initSoundPool(getActivity());// 初始化扫描的声音
        saomiao = new SaomiaoUtil(reader);// 创建扫描工具类
        dialogManager = new DialogManager(getActivity());
        zzxDialog = dialogManager.getZzxDialog();
        useDialog = dialogManager.getUserLoginDialog();
        deleteDialog = dialogManager.getDeleteDialog();
        loginDiolag = dialogManager.getLoginDialog();
        // 这里必须先获取当前的Activity 否则将不能找到 R.id.main_frame
        fm = getActivity().getSupportFragmentManager();
        receivelist = new ReciveList();
        rfidDevice = RFIDDevice.getInstance();
        createListener();
        rfidDevice.setOnDataReceiveListener(listener);

        initView();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                loginDiolag.dismiss();
                switch (msg.what) {
                    case 111:
                        // 视图显示
                        String zzxt = (String) msg.obj;
                        if ( listtest.contains(zzxt)) {
                            e(TAG, "已经包含了这个箱子" + zzxt);
                        } else {
                            if (boxlist.contains(zzxt) && !zzxt.equals("箱子规格不正确")) {
                                Util.play(1, 0);
                                listtest.add(zzxt);
                                break;
                            }
                        }
                        showView();
                        break;
                    case 3:// 提交成功
                        bundle.putString("cid", cid);
                        mCallback.onArticleSelected(RwwcFragment.TAG, bundle, KuguanFragment.this);
                        break;
                    case 1:// 提交失败
                        reSubmit();
                        zzxDialog.setTitle("超时链接");
                        break;
                    case 2:
                        reSubmit();
                        zzxDialog.setTitle("提交失败");
                        break;
                    case 10:// 获取登录框的回传值
                        Bundle bundle = msg.getData();
                        userId = bundle.getString("name");
                        pwd = bundle.getString("pwd");
                        if (userId.equals(fristUserId)) {// 如果相同，则提示用户已经验证
                            useDialog.show();
                            useDialog.setTitle("请换其他用户验证");
                        } else {
                            yanzhengUser(userId, pwd);
                        }

                        break;
                    case 11:
                        // 用户判断
                        checkLogin();
                        break;
                    case 12:
                        showBigToast(app.fanhuiMsg + "", 300);
                        useDialog.show();
                        break;
                    case 13:
                        showBigToast(app.fanhuiMsg + "", 300);
                        OnLoginClick();// 重新登录
                        break;
                }
            }
        };
        useDialog.setmHandler(handler);
        saomiao.setHandler(handler);
        return view;
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (mFingerUtil == null) {
            mFingerUtil = new FingerUtil(getActivity(), this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mFingerUtil != null) {
            mFingerUtil.stopFinger();
        }
    }

    /**
     * 初始化控件
     */
    public void initView() {
        zzxclear = (TextView) view.findViewById(R.id.zzx_clear_zx);
        zxlist_layout_view = (LinearLayout) view
                .findViewById(R.id.zxlist_layout_view);
        zxlist_layout = (LinearLayout) view.findViewById(R.id.zxlist_layout);// 填充器
        kg_name1 = (TextView) view.findViewById(R.id.kg_name1);// 库管员姓名1
        kg_name2 = (TextView) view.findViewById(R.id.kg_name2);// 库管员姓名2
        top = (TextView) view.findViewById(R.id.text_tyep_kg);// 顶部提示
        leftImage = (ImageView) view.findViewById(R.id.zhiwen1_kg);// 库管员指纹图1
        rightImage = (ImageView) view.findViewById(R.id.zhiwen2_kg);// 库管员指纹图2
        startsaomiao = (TextView) view.findViewById(R.id.startsaomiao_zx);// 开始扫描
        /*
         * 初始化与密码锁相关的变量
		 * @author zhouKai
		 */
        this.rg_zzx_num = (RadioGroup) view.findViewById(R.id.rg_zzx_num);// 周转箱编号单选组
        this.btn_lock_zzx = (Button) view.findViewById(R.id.btn_lock_zzx);    //闭锁
        this.btn_lock_zzx.setEnabled(false);
        this.btn_unLock_zzx = (Button) view.findViewById(R.id.btn_unLock_zzx);// 开锁
        this.btn_unLock_zzx.setEnabled(false);
        this.decodeLock = new DecodeLock(getActivity(), view, rg_zzx_num, btn_lock_zzx, btn_unLock_zzx,  listtest, zzx_queren);
        zzx_queren = (TextView) view.findViewById(R.id.zzx_queren);// 扫描确认按钮完成

        startsaomiao.setOnClickListener(this);
        zzxclear.setOnClickListener(this);
        bundle = getArguments();

        if (bundle != null) {
            cid = bundle.getString("cid");// 得到传过来的车牌号
            copylist = (ArrayList<String>) bundle.getSerializable("box");

            for (int i = 0; i < copylist.size(); i++) {
                boxlist.add(copylist.get(i));
            }
            wancenglist = (ArrayList<RenWuClass>) bundle
                    .getSerializable("list");
            // 得到父页面传过来的派工单
            for (int i = 0; i < wancenglist.size(); i++) {
                paigongdan += wancenglist.get(i).getPaigongDan() + "_";
            }
        }
        btn = (Button) view.findViewById(R.id.but_kg);//确定按钮
        btn.setOnClickListener(this);
        zzx_queren.setOnClickListener(this);
    }

    /**
     * 指纹通知消息
     */
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String data = msg.getData().getString("msg");
            System.out.println("data:=" + data);
            if (data != null && data.equals("获取指纹图像")) {
                top.setText("第一位人员正在验证指纹");
            } else if (data != null && data.equals("获取指纹图像成功")) {
                top.setText(data);
            }
        }
    };

    @Override
    public void onStart() {
        flag = true;// 初始化第一个人登录的标识
        if (listzou.size() > 0) {// 周转箱集合
            zxlist_layout_view.setVisibility(View.VISIBLE);
            zxlist_layout.setVisibility(View.GONE);// 显示填充器
        } else {
            zxlist_layout_view.setVisibility(View.GONE);
            zxlist_layout.setVisibility(View.VISIBLE);// 不显示填充器
        }
        super.onStart();
    }

    @Override
    public void onDestroy() {
        saomiao.close();
        if (reader != null) {// 关闭扫描功能
            reader.close();
        }
        super.onDestroy();
    }

    public void onClick(View arg0) {
        Log.e(TAG, "onClick*****" + decodeLock.mapstatesize());

        switch (arg0.getId()) {
            case R.id.but_kg:// 确定点击
            /*
             * 在拍照之前要求密码锁全部是闭锁状态
			 * @author zhouKai
			 * 掉用decodeLock
			 *
			 */

                System.out.print(testint = decodeLock.mapstatesize().size());
                if ((this.decodeLock.isUsed && this.decodeLock.isAllUnlocked()) && decodeLock.mapstatesize().size() == copylist.size()) {
                    String name2 = kg_name2.getText().toString();
                    if (null != name2 && !"".equals(name2)) {
                        // 弹出Dialog 提示是否要进行删除
                        zzxDialog.setTitle("是否提交");
                        zzxDialog.setPositiveButton("确定", new OnClickListener() {
                            public void onClick(View arg0) {
                                // 实际开发这里会调接口 修改状态
                                submit();
                            }
                        }).setNegativeButton("取消", new OnClickListener() {
                            public void onClick(View arg0) {

                            }
                        }).show();
                    } else {
                        saomiao.close();
                        fingerLogin("库管员登陆");
                    }
                }
                break;
            case R.id.startsaomiao_zx: // 开始扫描
                saoMiaolock();
                e(TAG, "查锁");
            /*
             * 只有当使用密码锁时，才显示按钮 zzx_queren
			 * @author zhouKai
			 */
                if (this.decodeLock.isUsed) {
                    this.zzx_queren.setVisibility(View.GONE);
                }
                this.btn_lock_zzx.setEnabled(true);
                this.btn_unLock_zzx.setEnabled(true);
                btn.setBackgroundColor(Color.parseColor("#6ECFF5"));//蓝色
                break;
            case R.id.zzx_clear_zx:// 重新扫描
                boxlist.clear();
                if (bundle != null) {
                    for (int i = 0; i < copylist.size(); i++) {
                        boxlist.add(copylist.get(i));
                    }
                }
                btn.setEnabled(false);
                btn.setBackgroundResource(R.drawable.gray_btn_bg);
                searchLocknew();//重新扫描方法
                listtest.clear();
            /*
             * 更新界面，显示扫描到的周转箱
			 * @author zhouKai
			 */
                this.decodeLock.notifyZzxNumListChange();
                this.btn_lock_zzx.setEnabled(false);
                this.btn_unLock_zzx.setEnabled(false);
                break;
            case R.id.zzx_queren:
                saomiao.close();
                this.btn_lock_zzx.setEnabled(true);
                this.btn_unLock_zzx.setEnabled(true);
                btn.setBackgroundColor(Color.parseColor("#6ECFF5"));
                break;
        }
    }

    /**
     * 用户验证
     */
    public void yanzhengUser(final String name, final String pwd) {
        loginDiolag.show();
        loginDiolag.setMessage("正在验证用户...");
        new Thread(new Runnable() {
            public void run() {
                try {
                    user = UpServer.login(name, pwd);
                    if (user != null) {
                        handler.sendEmptyMessage(11);
                    } else {
                        handler.sendEmptyMessage(12);// 查无此人信息
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(12);// 查无此人信息
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(13);// 登录异常
                }
            }
        }).start();
    }

    /**
     * dialog no dismiss
     */
    OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };

    /**
     * 提交最后的信息
     */
    public void submit() {
        loginDiolag.show();
        loginDiolag.setMessage("提交中...");
        new Thread(new Runnable() {
            public void run() {
                try {
                    String result = UpServer.setHuiKu(paigongdan,
                            app.userZhanghao, kuId);
                    Log.e(TAG, "result=====" + result);//查看result的结果
                    if ("success".equals(result)) {
                        handler.sendEmptyMessage(3);
                    } else {
                        handler.sendEmptyMessage(2);
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(1);
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    /**
     * 重试
     */
    public void reSubmit() {
        Log.e(TAG, "reSubmit*****" + decodeLock.mapstatesize());
        zzxDialog.show();
        zzxDialog.setGone();
        zzxDialog.setPositiveButton("重试", new OnClickListener() {
            public void onClick(View arg0) {
                // 实际开发这里会调接口 修改状态
                submit();
            }
        }).setNegativeButton("取消", new OnClickListener() {
            public void onClick(View arg0) {

            }
        });
    }

    /**
     * 用户登录失败重试
     */
    public void OnLoginClick() {
        deleteDialog.show();
        deleteDialog.setTitle("登录异常");
        deleteDialog.setPositiveButton("重试", new OnClickListener() {
            public void onClick(View arg0) {
                yanzhengUser(userId, pwd);
            }
        });
        deleteDialog.setNegativeButton("取消", new OnClickListener() {
            public void onClick(View arg0) {
            }
        });
    }

    /**
     * 视图显示
     */
    public void showView() {
        if (listzou.size() > 0) {
            zxlist_layout_view.setVisibility(View.VISIBLE);
            zxlist_layout.setVisibility(View.GONE);
        } else {
            zxlist_layout_view.setVisibility(View.GONE);
            zxlist_layout.setVisibility(View.VISIBLE);
        }
        /*
         * 更新界面，显示扫描到的周转箱
		 * @author zhouKai
		 */
        this.decodeLock.notifyZzxNumListChange();
        System.out.println("集合长度：=" + copylist.size());
        for (int i = 0; i < copylist.size(); i++) {
            System.out.println(copylist.get(i));
        }

        if (copylist.size() == listzou.size()) {
            btn.setEnabled(true);
            btn.setBackgroundResource(R.drawable.buttom_selector_bg);
        } else {
            showBigToast("请检查箱子数量是否正确", 100);
            e(TAG, "copylistt=" + copylist.size());
            btn.setEnabled(false);
            btn.setBackgroundResource(R.drawable.gray_btn_bg);
        }
    }

    /**
     * 用户判断
     */
    public void checkLogin() {
        Log.e(TAG, "checkLogin*****" + decodeLock.mapstatesize());

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    String result = UpServer.getJigouLeibie(user
                            .getOrganizationId());
                    if ("0".equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                if (TextUtils.isEmpty(kg_name1.getText()
                                        .toString())) {

                                    if (user.getUserId().equals(
                                            Constant.KgRoleId)) {// 库管员登录
                                        kuId = userId + "_";

                                        kg_name1.setText(user.getName());
                                        leftImage.setImageBitmap(null);
                                        leftImage
                                                .setBackgroundResource(R.drawable.sccuss);
                                        if (flag) {
                                            fristUserId = userId;// 保存第一个人登录的账号
                                            flag = false;
                                        }

                                        showBigToast("请总行库管二进行指纹验证..", 500);
                                        mFingerUtil.startControl();
                                    } else {
                                        fingerLogin("总行库管员登陆");
                                    }
                                } else {
                                    if (user.getUserId().equals(
                                            Constant.KgRoleId)) {// 库管员登录
                                        kuId = kuId + userId;
                                        kg_name2.setText(user.getName());
                                        rightImage.setImageBitmap(null);
                                        rightImage
                                                .setBackgroundResource(R.drawable.sccuss);
                                        // 弹出Dialog 提示是否要进行删除

                                        zzxDialog.setTitle("是否提交");
                                        zzxDialog
                                                .setPositiveButton("确定",
                                                        new OnClickListener() {
                                                            public void onClick(
                                                                    View arg0) {
                                                                // 实际开发这里会调接口
                                                                // 修改状态
                                                                if (decodeLock.mapstatesize().size() == copylist.size()) {
                                                                    submit();
                                                                }

                                                            }
                                                        })
                                                .setNegativeButton("取消",
                                                        new OnClickListener() {
                                                            public void onClick(
                                                                    View arg0) {

                                                            }
                                                        }).show();
                                    } else {
                                        fingerLogin("总行库管员二登陆");
                                    }
                                }

                            }
                        });
                    } else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showBigToast("您不是总行库管", 500);
                            }
                        });
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    /**
     * 库管验证
     */
    private void kuGuanConfirm(User user) {
        Log.e(TAG, "kuGuanConfirm*****" + decodeLock.mapstatesize());
        String k1 = kg_name1.getText().toString();
        if (TextUtils.isEmpty(k1)) {
            kuId = userId + "_";
            kg_name1.setText(user.getName());
            leftImage.setImageBitmap(null);
            leftImage.setBackgroundResource(R.drawable.sccuss);
            fristUserId = userId;
            showBigToast("请总行库管二进行指纹验证..", 500);
            mFingerUtil.startControl();
        } else {
            kuId = kuId + userId;
            kg_name2.setText(user.getName());
            rightImage.setImageBitmap(null);
            rightImage.setBackgroundResource(R.drawable.sccuss);
            Log.e("kgf",""+decodeLock.mapstatesize().size()+copylist.size());
            if (decodeLock.mapstatesize().size() ==copylist.size() && decodeLock.isAllUnlocked() == true) {
                zzxDialog.setTitle("是否提交");
                zzxDialog.setPositiveButton("确定", new OnClickListener() {
                    public void onClick(View arg0) {
                        // 实际开发这里会调接口
                        // 修改状态
                        submit();


                    }

                }).setNegativeButton("取消", new OnClickListener() {
                    public void onClick(View arg0) {

                    }
                }).show();
            } else {
                Log.e("kgf","长度！！！！！！！！！！！！！！！"+decodeLock.mapstatesize().size()+copylist.size());
                showBigToast("请处理锁", 1000);
            }

        }
    }

    @Override
    public void getFingerValue(byte[] value) {
        mFingerUtil.stopControl();
        String corpId;
        String roleId;
        corpId = DEPARTMENT_ID;
        roleId = Constant.KgRoleId;
        mFingerUtil.startTconfrim(corpId, roleId, value);

    }

    /**
     * 总行库管登陆
     */
    public void fingerLogin(String title) {
        if (threeTimes == true) {
            useDialog.show();// 弹出登录
            useDialog.setTitle(title);
            mFingerUtil.stopControl();
            return;
        }
        showBigToast("请总库库管验证指纹..", 500);
        if (mFingerUtil.getThread() == null) {
            mFingerUtil.startFinger();
        } else {
            mFingerUtil.startControl();
        }
    }

    @Override
    public void getFingerBitmap(Bitmap bitmap) {
        String iv3 = kg_name1.getText().toString();
        if (TextUtils.isEmpty(iv3)) {
            leftImage.setImageBitmap(bitmap);
        } else {
            rightImage.setImageBitmap(bitmap);
        }
    }

    /**
     * 指纹验证成功
     */
    @Override
    public void getFingerSuccess(User user) {
        user.setOrganizationId(DEPARTMENT_ID);
        user.setUserId(Constant.KgRoleId);
        userId = user.getAccount();
        if (user.getName().equals(kg_name1.getText().toString())) {
            showBigToast("用户重复验证,请重试...", 800);
            mFingerUtil.startControl();
            return;
        }
        times = 0;
        kuGuanConfirm(user);
    }

    /*
    * 指纹验证失败*/
    @Override
    public void getFingerFail() {
        times++;
        if (times == 3) {
            threeTimes = true;
        } else {
            threeTimes = false;
        }
        new DeleteDialog(getActivity())
                .builder()
                .setTitle(
                        times == 3 ? "指纹验证失败3次,请使用密码登陆" : "指纹验证失败" + times
                                + "次")
                .setOnlyButton()
                .setkeyListener(keylistener)
                .setPositiveButton(times == 3 ? "密码登陆" : "重新验证",
                        new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {
                                leftImage.setImageBitmap(null);
                                rightImage.setImageBitmap(null);
                                // fingerHandler.sendMessageDelayed(fingerHandler.obtainMessage(21),
                                // 50);

								/* 判断错误次数，3次打开密码登陆界面 */
                                if (times == 3) {
                                    times = 0;
                                    useDialog.clear();
                                    useDialog.show();
                                    return;
                                }
                                /* 开启指纹数据发送开关 */
                                mFingerUtil.startControl();
                            }
                        }).show();
    }

    /**
     * 新版的开锁功能 查找到新的锁号码添加到集合中准备传值
     */

    //简化版开锁
    public void searchLocknew() {
        byte[] reply = null;
        int locknum = 0;
        int count = 0;
        List<String> rfidSerialID = new ArrayList();
        selectItem = "";
        String epcStr = "";
        receivelist.removeAllElement();
        rfidDevice.unSelectMode();
        createListener();//接收有效字节并实心抽象实现方法需要先覆盖发出发接收方法
        rfidDevice.searchEPC();//发送消息命令
        String zhou = "";
        int replynum = receivelist.getElementNum();
        for (int i = 0; i < replynum; i++) {
            e(TAG, "系统时间" + System.currentTimeMillis());
            reply = receivelist.getFinishElement();//轮询
            String replyString = com.poka_global_constant.Util.byte2HexStr(reply);
            if (!replyString.equals("BB01FF000115167E") && replyString.length() > 40) {
                LockID.add(replyString.substring(16, 40));
                rfidDevice.unSelectMode();
                rfidDevice.selectMode();
                reply = receivelist.getFinishElement();
                //限制普通标签被查到并添加到集合

                String strBox = null;
                list.clear();
                if (list.contains(replyString.substring(16, 40))) {
                    e(TAG, "包含了此箱不添加");
                } else {

                    list.add(replyString.substring(16, 40));//将锁箱号码放到集合传入到开锁界面
                    epcStr = replyString.substring(16, 40);
                    strBox = epcStr;
                    zhou = Guolv(strBox);
                    e(TAG, "kg=" + zhou);
                    if (copylist.contains(zhou) && boxlist.contains(zhou) && !zhou.equals("箱子规格不正确")) {
                        if (copylist.contains(zhou) && !listzou.contains(zhou)) {
                            Util.play(1, 0);
                            listzou.add(zhou);
                            handlerzhuan = decodeLock.getHandler();
                            Message msg = new Message();
                            msg.obj = strBox;
                            msg.what = 992; //发送到decodelock  类进行添加集合
                            if (null != strBox && !"".equals(strBox)) {
                                handlerzhuan.sendMessage(msg);
                            }
                            rfidDevice.unSelectMode();
                            if (listzou.size() > 0) {// 周转箱集合
                                rfidDevice.closeRFID();
                                zxlist_layout_view.setVisibility(View.VISIBLE);
                                zxlist_layout.setVisibility(View.GONE);// 显示填充器
                            } else {
                                zxlist_layout_view.setVisibility(View.GONE);
                                zxlist_layout.setVisibility(View.VISIBLE);// 不显示填充器
                            }
                            if (copylist.size() == listzou.size()) {
                                btn.setEnabled(true);
                                btn.setBackgroundResource(R.drawable.buttom_selector_bg);
                            } else {
                                if (btn.isClickable() == true && copylist.size() != listzou.size()) {
                                    showBigToast("" + "当前的箱子数量为："+listzou.size()+"请核实箱子数量", 100);
                                }

                                btn.setEnabled(false);

                                btn.setBackgroundResource(R.drawable.gray_btn_bg);
                            }

                        }

                        if (count == GlobalConstant.TRY_TICK) {
                            continue;
                        }
                        locknum++;
                    }
                }


            }
        }
    }


    /**
     * 过滤器
     *
     * @param str
     * @return
     */
    public String Guolv(String str) {
        String box = CaseString.getBoxNum(str);//这个方法以后自己去修改
        if (box.length() < 2) {
            return "";
        }
        String stx = box.substring(box.length() - 2, box.length());
        if ("ZZ".equals(stx)) {
            return box;
        } else {
            return "箱子规格不正确";
        }
    }

    /**
     * 自定义 toast， 增大字体
     *
     * @param info     提示信息
     * @param duration 显示时间，0：短时间，1：长时间
     */
    private void showBigToast(String info, int duration) {
        Toast toast = new Toast(getActivity());
        toast.setGravity(Gravity.CENTER, 0, 0);
        TextView tv = new TextView(getActivity());
        tv.setBackgroundResource(R.drawable.bg_toast);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(25, 5, 25, 5);
        tv.setTextColor(Color.WHITE);
        tv.setText(info);
        tv.setTextSize(30);
        toast.setView(tv);
        toast.setDuration(duration);
        toast.show();
    }

    /*****
     * 循环开启扫描
     */
    private void saoMiaolock() {//  点击按钮时停止循环 点击   当集合中数据满足条件时 停止循环

        rfidDevice = RFIDDevice.getInstance();//new对象
        LastClickTime = System.currentTimeMillis();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        searchLocknew();
        LastClickTime1 = System.currentTimeMillis();
        lctime = LastClickTime - LastClickTime1;
        e(TAG, "copylist.size()" + copylist.size());
        if (copylist.size() == 1 || lctime > 5000) {//copy.list 是获取从另一个界面传值得到的
            istestflag = true;
        }


    }

    /***
     * 创建监听事件
     */
    private void createListener() {
        listener = new RFIDDevice.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {
                // TODO Auto-generated method stub
                // 如果接收序列为空直接将数据加入到接收序列中,
                byte[] tempbuffer = null;
                if (receivelist.getElementNum() != 0 && !receivelist.getLastElementStatus()) {
                    byte[] lastbuf = receivelist.getLastElement();
                    tempbuffer = new byte[lastbuf.length + size];
                    System.arraycopy(lastbuf, 0, tempbuffer, 0, lastbuf.length);
                    System.arraycopy(buffer, 0, tempbuffer, lastbuf.length, size);
                    receivelist.removeLastElement();
                } else {
                    tempbuffer = new byte[size];
                    System.arraycopy(buffer, 0, tempbuffer, 0, size);
                }
                // 按照接收buffer的最后一字节判断是否接收完毕
                if ((tempbuffer[0] == (byte) 0xBB && tempbuffer.length < 5) || (tempbuffer[0] == (byte) 0xBB && tempbuffer.length >= 5 && (tempbuffer[4] + 7) > tempbuffer.length))
                    receivelist.addElement(tempbuffer, false);
                if ((tempbuffer[0] == (byte) 0xBB && tempbuffer.length >= 5 && ((int) tempbuffer[4] + 7) <= tempbuffer.length)) {
                    int bytelen = tempbuffer[4] + 7;
                    byte[] newbyte = new byte[bytelen];
                    System.arraycopy(tempbuffer, 0, newbyte, 0, bytelen);
                    receivelist.addElement(newbyte, true);
                    if ((tempbuffer.length - bytelen) > 0) {
                        newbyte = new byte[tempbuffer.length - bytelen];
                        System.arraycopy(tempbuffer, bytelen, newbyte, 0, tempbuffer.length - bytelen);
                        receivelist.addElement(newbyte, false);
                    }
                }
            }
        };
        rfidDevice.setOnDataReceiveListener(listener);
    }

    /**
     * 是否为第一次点击
     * @return
     */
    private boolean isfastDoubleClick() {
        Long time = System.currentTimeMillis();
        Long timeDouble = time - LastClickTime;
        Log.i(TAG, "lsn timeDouble = " + timeDouble);
        if (0 < timeDouble && timeDouble < 600) {
            return true;
        }
        LastClickTime = time;
        return false;
    }
}
